﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    class SimpleServer : Server
    {
        Socket acceptedSocket_;
        public SimpleServer(int port)
            :base(port)
        {
            
        }
        override public void Start()
        {
            address_ = GetLocalIPAddress();
            endPoint_ = new IPEndPoint(address_, port_);
            listener_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener_.Bind(endPoint_);
            listener_.Listen(1000);

            while (true)
            {
                try
                {
                    Console.WriteLine("IP: {0}", endPoint_.ToString());
                    Console.WriteLine("Listen...");
                    acceptedSocket_ = listener_.Accept();
                    Console.WriteLine("Connected IP: {0}", acceptedSocket_.RemoteEndPoint.ToString());
                    byte[] packet = new byte[2048];
                    int packetLen = acceptedSocket_.Receive(packet);
                    Console.WriteLine("packet: {0}", packet.ToString());
                    
                }


                catch (System.Net.Sockets.SocketException sock_exception)
                {
                    Console.WriteLine("[SocketError]:{0}", sock_exception.Message);
                }
                catch (System.Exception common_exception)
                {
                    Console.WriteLine("[Common Error]:{0}", common_exception.Message);
                }
            }
            
        }
        override public void Stop()
        {
            listener_.Close();
        }
    }
}
